package cn.bugstack.xfg.dev.tech.interceptor;

import cn.bugstack.chatglm.session.Configuration;
import cn.bugstack.chatglm.utils.BearerTokenUtils;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;

/**
 * @description 接口拦截器
 *
 */
public class OpenAiHTTPInterceptor implements Interceptor {

    /**
     * 智普Ai，Jwt加密Token
     */
    private final Configuration configuration;

    public OpenAiHTTPInterceptor(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public @NotNull Response intercept(Chain chain) throws IOException {
        // 1. 获取原始 Request (通过 chain 直接构建新请求，避免使用 original.newBuilder())
        Request original = chain.request();

        // 2. 直接构建新请求，不依赖 original 的 newBuilder() 方法
        Request.Builder requestBuilder = new Request.Builder()
                .url(original.url())
                .header("Authorization", "Bearer " + BearerTokenUtils.getToken(
                        configuration.getApiKey(),
                        configuration.getApiSecret()
                ))
                .header("Content-Type", Configuration.JSON_CONTENT_TYPE)
                .header("User-Agent", Configuration.DEFAULT_USER_AGENT);

        // 处理 Accept 头
        String acceptHeader = original.header("Accept");
        if (acceptHeader != null) {
            requestBuilder.header("Accept", acceptHeader);
        } else {
            requestBuilder.header("Accept", Configuration.SSE_CONTENT_TYPE);
        }

        // 复制原始请求的方法和 body
        requestBuilder.method(original.method(), original.body());

        // 3. 构建并执行请求
        return chain.proceed(requestBuilder.build());
    }
    }

